/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hadss_intents/hadss_intents.dart';
import 'package:ohfeature_sample/intents/utils/json_data.dart';
import 'package:ohfeature_sample/intents/utils/overlay_toast.dart';
import '../l10n/generated/app_localizations.dart';

// 意图框架页面
class IntentsHomePage extends StatefulWidget {
  const IntentsHomePage({super.key});

  @override
  State<IntentsHomePage> createState() => _IntentsHomePageState();
}

class _IntentsHomePageState extends State<IntentsHomePage>
    with SingleTickerProviderStateMixin {
  // 当前选中的按钮索引，-1表示未选中
  int _selectedIndex = -1;
  // 文本控制器
  final TextEditingController _textController = TextEditingController();
  final _intentsPlugin = Intents();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _textController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 获取本地化字符串
    AppLocalizations il8n = AppLocalizations.of(context)!;
    // 按钮文字
    final List<String> _buttonTexts = [
      '${il8n.music}insightIntents',
      '${il8n.video}insightIntents',
      '${il8n.music}deleteIntent',
      '${il8n.video}deleteIntent',
      '${il8n.music}deleteEntity',
      '${il8n.video}deleteEntity',
      'getSid',
      'getSidRenew',
      'shareIntent',
      'deleteIntent',
      'deleteEntity'
    ];
    return Scaffold(
      appBar: _buildAppBar(),
      resizeToAvoidBottomInset: true,
      backgroundColor: Colors.grey[100], // 设置整体背景为浅灰色
      body: SingleChildScrollView(
        padding: EdgeInsets.only(
          bottom: MediaQuery.of(context).viewInsets.bottom,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              alignment: Alignment.centerLeft,
              margin: const EdgeInsets.only(left: 16, top: 16),
              child: const Text(
                'Lnsightintent Test',
                style: TextStyle(
                    fontWeight: FontWeight.w700,
                    fontSize: 30,
                    color: Colors.black),
              ),
            ),
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: _buildTextField(),
              ),
            ),
            // 按钮区
            Column(
              mainAxisSize: MainAxisSize.min,
              children: _buttonTexts.asMap().entries.map((entry) {
                return _buildCustomButton(entry.key, _buttonTexts[entry.key]);
              }).toList(),
            ),
            const SizedBox(height: 24), // 底部留白
          ],
        ),
      ),
    );
  }

  // 创建导航栏组件
  AppBar _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.grey[100],
      elevation: 0,
      leading: IconButton(
          onPressed: () {
            Navigator.pop(context);
          },
          icon: Image.asset(
            'lib/assets/images/back.png',
            width: 40,
            height: 40,
          )),
    );
  }

  // 创建按钮
  Widget _buildCustomButton(int index, String buttonText) {
    final isSelected = _selectedIndex == index;
    return GestureDetector(
      onTap: () => _handleButtonTap(index),
      behavior: HitTestBehavior.translucent,
      child: Container(
        margin: const EdgeInsets.only(left: 16, right: 16, bottom: 12),
        height: 40,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: isSelected
                ? Color.fromRGBO(10, 89, 247, 1)
                : Color.fromRGBO(0, 0, 0, 0.05),
            borderRadius: BorderRadius.circular(20)),
        child: Text(
          buttonText,
          style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color:
                  isSelected ? Colors.white : Color.fromRGBO(10, 89, 247, 1)),
        ),
      ),
    );
  }

  // 输入框组件
  Widget _buildTextField() {
    // 获取本地化字符串
    AppLocalizations il8n = AppLocalizations.of(context)!;
    return TextField(
      controller: _textController,
      minLines: 1,
      maxLines: 100, // 允许换行
      maxLength: 10000, // 最大字符数
      maxLengthEnforcement: MaxLengthEnforcement.enforced, // 达到最大值后禁止输入
      decoration: InputDecoration(
        border: InputBorder.none,
        hintText: il8n.hintText,
        hintStyle: const TextStyle(color: Colors.grey),
      ),
    );
  }

  // 按钮点击响应事件
  void _handleButtonTap(int index) {
    setState(() {
      if (_selectedIndex == index) {
        _selectedIndex = -1;
      } else {
        _selectedIndex = index;
      }
    });

    _intentsAction(index);
  }

  // 意图框架事件
  _intentsAction(int index) {
    if (index == 0 || index == 1) {
      doGetShareIntent(index);
      return;
    }
    if (index == 2 || index == 3) {
      doGetDeleteIntent(index);
      return;
    }
    if (index == 4 || index == 5) {
      doGetDeleteEntity(index);
      return;
    }
    if (index == 6 || index == 7) {
      doGetSide(index);
      return;
    }
    if (index == 8) {
      shareIntent();
      return;
    }
    if (index == 9) {
      doDeleteIntent();
      return;
    }
    if (index == 10) {
      doDeleteEntity();
      return;
    }
  }

  // 分享意图
  void shareIntent() {
    // 获取本地化字符串
    AppLocalizations il8n = AppLocalizations.of(context)!;
    if (_textController.text.isEmpty) {
      OverlayToast.show(context, il8n.toast);
      return;
    }
    try {
      Map<dynamic, dynamic> shareData =
          jsonDecode(_textController.text) as Map<String, dynamic>;
      List<InsightIntent> list = [];
      InsightIntent intent = InsightIntent();
      intent.identifier = shareData['identifier'];
      intent.intentVersion = shareData['intentVersion'];
      intent.intentName = shareData['intentName'];
      intent.intentActionInfo =
          Map<String, Object>.from(shareData['intentActionInfo'] ?? {});
      intent.intentEntityInfo =
          Map<String, Object>.from(shareData['intentEntityInfo'] ?? {});
      list.add(intent);

      _intentsPlugin.shareIntent(list).then(
          (value) => {
                OverlayToast.show(context, "${il8n.success}！"),
              },
          onError: (err) => {
                OverlayToast.show(
                    context, "${intent.intentName}${il8n.fail}： $err"),
              });
    } catch (e) {
      OverlayToast.show(context, il8n.data);
    }
  }

  // 获取意图数据
  void doGetShareIntent(int index) {
    Map<dynamic, dynamic> shareData = index == 0
        ? JsonDataUtil().shareMusicIntent
        : JsonDataUtil().shareVideoIntent;
    setState(() {
      _textController.text = jsonEncode(shareData);
    });
  }

  // 获取deleteIntent
  void doGetDeleteIntent(int index) {
    Map<dynamic, dynamic> shareData = index == 2
        ? JsonDataUtil().musicDeleteIntent
        : JsonDataUtil().videoDeleteIntent;
    setState(() {
      _textController.text = jsonEncode(shareData);
    });
  }

  // 获取deleteEntity
  void doGetDeleteEntity(int index) {
    Map<dynamic, dynamic> shareData = index == 4
        ? JsonDataUtil().musicDeleteEntity
        : JsonDataUtil().videoDeleteEntity;
    setState(() {
      _textController.text = jsonEncode(shareData);
    });
  }

  // 获取side
  void doGetSide(int index) {
    bool isNew = index == 6 ? false : true;
    String error = index == 6 ? 'getSid error:' : 'getSidRenew error:';
    try {
      _intentsPlugin.getSide(isNew).then(
          (value) => setState(() {
                _textController.text = value.toString();
              }),
          onError: (err) => {
                OverlayToast.show(context, "$error${err.toString()}"),
              });
    } catch (e) {
      OverlayToast.show(context, "$error${e.toString()}");
    }
  }

  // 删除DeleteIntent
  void doDeleteIntent() {
    // 获取本地化字符串
    AppLocalizations il8n = AppLocalizations.of(context)!;
    if (_textController.text.isEmpty) {
      OverlayToast.show(context, il8n.toast);
      return;
    }

    try {
      Map<dynamic, dynamic> shareData =
          jsonDecode(_textController.text) as Map<String, dynamic>;

      try {
        _intentsPlugin.deleteIntent(shareData['intentName']).then(
            (value) => setState(() {
                  _textController.text = '';
                  OverlayToast.show(context, '${il8n.success}！');
                }),
            onError: (err) => {
                  OverlayToast.show(context, 'doDeleteIntent : error $err'),
                });
      } catch (e) {
        OverlayToast.show(context, 'doDeleteIntent error = ${e.toString()}');
      }
    } catch (e) {
      OverlayToast.show(context, il8n.data);
    }
  }

  // 删除DeleteEntity
  void doDeleteEntity() {
    // 获取本地化字符串
    AppLocalizations il8n = AppLocalizations.of(context)!;
    if (_textController.text.isEmpty) {
      OverlayToast.show(context, il8n.toast);
      return;
    }
    try {
      Map<dynamic, dynamic> shareData =
          jsonDecode(_textController.text) as Map<String, dynamic>;
      List<dynamic> entityIds = shareData['entityIds'];
      try {
        _intentsPlugin
            .deleteEntity(shareData['entityName'], entityIds.cast<String>())
            .then(
                (value) => setState(() {
                      OverlayToast.show(context, "${il8n.success}！");

                      _textController.text = '';
                    }),
                onError: (err) => {
                      OverlayToast.show(context, 'doDeleteEntity : error $err'),
                    });
      } catch (e) {
        OverlayToast.show(context, 'doDeleteIntent : error $e');
      }
    } catch (e) {
      OverlayToast.show(context, il8n.data);
    }
  }
}
